<?php
/**
 * Login Class
 *
 */
class Login extends Controller {
	/**
	 * Constructor
	 */
	function login()
		{
			parent::Controller();
			$this->load->model('Login_model', '', TRUE);
			$this->load->model('Cabang_model', '', TRUE);
		}
	
	/**
	 * Memeriksa user state, jika dalam keadaan login akan menampilkan halaman user,
	 * jika tidak akan meload halaman login
	 */
	function index()
	{
		if ($this->session->userdata('login') == TRUE)
		{
			redirect('home');
		}
		else
		{
			$this->load->view('login/login_view');
		}
	}
	
	/**
	 * Memproses login
	 */
	function process_login()
	{
		$this->form_validation->set_rules('user_name', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('id_cabang', 'id_cabang', 'required');
		
		
		if ($this->form_validation->run() == TRUE)
		{
			$user_name = $this->input->post('user_name');
			$password = $this->input->post('password');
			$id_cabang = $this->input->post('id_cabang');
			
			if ($this->Login_model->check_user($user_name, $password, $id_cabang) == TRUE)
			{
				$query = $this->Login_model->get_logged_user($user_name);
					foreach ($query as $row)
					{
						$id_user = $row->id_user;
						$usergroup = $row->usergroup;
						$id_cabang = $row->id_cabang;
						$cabang = $row->cabang;
						$id_usergroup = $row->id_usergroup;
					}
				$data = array('id_user' => $id_user, 'user_name' => $user_name, 'login' => TRUE, 'usergroup' => $usergroup,
							'id_cabang' => $id_cabang, 'cabang' => $cabang,
							'id_usergroup' => $id_usergroup,
							'login_date' => date("l, d-M-Y"), 'login_time' => date("h:i:s A"),
							'analisa' => FALSE);		
				$this->session->set_userdata($data);
				redirect('home');
			}
			else
			{
				$this->session->set_flashdata('message', 'Maaf, nama user, password dan/atau id cabang Anda salah');
				redirect('login/index');
			}
		}
		else
		{
			$this->load->view('login/login_view');
		}
	}
	
	/**
	 * Memproses logout
	 */
	function process_logout()
	{
		$this->session->sess_destroy();
		redirect('login', 'refresh');
	}
	
	} //end class